/*
 * FXGL - JavaFX Game Library. The MIT License (MIT).
 * Copyright (c) AlmasB (almaslvl@gmail.com).
 * See LICENSE for details.
 */

package com.windea.study.kotlin.fxgl.sample.sandbox.achievements

import com.almasb.fxgl.achievement.*
import com.almasb.fxgl.app.*
import com.almasb.fxgl.dsl.*
import com.almasb.fxgl.saving.*
import javafx.event.*
import javafx.scene.input.*
import java.util.*

/**
 *
 *
 * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com)
 */
class AchievementApp : GameApplication() {
	override fun initSettings(settings: GameSettings) {
		settings.achievements = listOf(
			Achievement("See the world", "Move 600 pixels", "pixelsMoved", 600),
			Achievement("Killer", "Kill 3 enemies", "enemiesKilled", 3)
		)
		
		settings.isMenuEnabled = true
		settings.enabledMenuItems = EnumSet.allOf(MenuItem::class.java)
	}
	
	override fun initGameVars(vars: MutableMap<String, Any>) {
		vars["pixelsMoved"] = 0
		vars["enemiesKilled"] = 0
	}
	
	override fun initGame() {
		getEventBus().addEventHandler(AchievementEvent.ANY, EventHandler { e -> println(e) })
	}
	
	override fun initInput() {
		onKeyDown(KeyCode.Q, "save") {
			val data = saveState()
			
			FXGL.getFS().writeDataTask(data, "data.dat").run()
		}
		
		onKeyDown(KeyCode.E, "Load") {
			FXGL.getFS().readDataTask<DataFile>("data.dat")
				.onSuccess { data -> loadState(data) }
				.run()
		}
		
		onKeyDown(KeyCode.A, "Dec") { FXGL.inc("enemiesKilled", -1) }
		
		onKeyDown(KeyCode.D, "Inc") { FXGL.inc("enemiesKilled", +1) }
	}
	
	override fun saveState(): DataFile {
		val map = HashMap<String, Int>()
		
		map["pixelsMoved"] = geti("pixelsMoved")
		map["enemiesKilled"] = geti("enemiesKilled")
		
		return DataFile(map)
	}
	
	@Suppress("UNCHECKED_CAST")
	override fun loadState(dataFile: DataFile) {
		val map = dataFile.data as Map<String, Int>
		
		set("pixelsMoved", map.getValue("pixelsMoved"))
		set("enemiesKilled", map.getValue("enemiesKilled"))
	}
}

fun main(args: Array<String>) {
	GameApplication.launch(AchievementApp::class.java, args)
}

